package com.example.demo.concurrent.ReentrantReadWriteLock.cacheData;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-04-17
 * Time: 12:23
 */

public class CacheData1 {
    //读写时用的数据
    private Object data;
    //读写锁
    private ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
    //缓存是否失效
    private volatile boolean cacheValid;

    public void processCacheData() {
        //读加锁,为了防止其他线程写的干扰
        rw.readLock().lock();

        if(!cacheValid) {//缓存失效了,需要将新的数据写入缓存
            //释放读锁
            rw.readLock().unlock();
            //获取写入将新数据写入缓存
            rw.writeLock().lock();
            try{
                if(!cacheValid) {//缓存失效,再次进行判断,看是否有其他线程写入了
                    data = 999;
                    cacheValid = true;//缓存生效
                }
                rw.readLock().lock();
            }finally {
                rw.writeLock().unlock();
            }
        }

        try{
            //缓存没有失效,则直接缓存中的数据
            use(data);
        }finally {
            //读锁释放
            rw.readLock().unlock();
        }

    }

    private Object use(Object data) {
        return data;
    }

}
